/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.transport.ptcp.psocket;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Enumeration;
import java.util.Hashtable;

import cgl.narada.transport.ptcp.psocket.tools.PTCPParameters;
import cgl.narada.transport.ptcp.psocket.tools.PTCPSocketInfo;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2004</p>
 * <p>Company: </p>
 * @author not attributable
 * @version 1.0
 */
public class PTCPServerSocket implements PTCPParameters {
  private Hashtable clients_ = null;
  private ServerSocket server_socket_ = null; //Internal server connection socket.
  private String module_name_ = "PTCPServerSocket: ";

  public PTCPServerSocket() {
    clients_ = new Hashtable();
  }

  /**
   * Constructor.
   *
   * Creates a server socket on a specified port. A port of 0 creates
   * a socket on any free port.
   *
   * The maximum queue length for incoming connection indications
   * (a request to connect) is set to 50. If a
   * connection indication arrives when the queue is full,
   * the connection is refused.
   */
  public PTCPServerSocket(int port) {
    try {
      /*SocketAddress sockaddr = null;
             sockaddr      = new InetSocketAddress(port);
             serverSocket_ = new ServerSocket();
             serverSocket_.setReceiveBufferSize(62 * 1024);
             serverSocket_.bind(sockaddr);
       */
      clients_ = new Hashtable();
      server_socket_ = new ServerSocket(port);
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }
  }

  /**
   * Constructor.
   * Creates a server socket and binds it to the specified local port number,
   * with the specified backlog. A port number of 0 creates a socket on
   * any free port.
   *
   * The maximum queue length for incoming connection indications
   * (a request to connect) is set to the backlog parameter.
   * If a connection indication arrives when the queue is full,
   * the connection is refused.
   */
  public PTCPServerSocket(int port, int backlog) {
    try {
      clients_ = new Hashtable();
      server_socket_ = new ServerSocket(port, backlog);
    }
    catch (IOException ex) {
    }
  }

  /**
   * Constructor.
   * Create a server with the specified port, listen backlog,
   * and local IP address to bind to. The bindAddr
   * argument can be used on a multi-homed host for a ServerSocket
   * that will only accept connect requests to one of its addresses.
   * If bindAddr is null, it will default accepting connections on
   * any/all local addresses. The port must be between 0 and 65535,
   * inclusive.
   */
  public PTCPServerSocket(int port, int backlog, InetAddress bindAddr) {
    try {
      clients_ = new Hashtable();
      server_socket_ = new ServerSocket(port, backlog, bindAddr);
    }
    catch (IOException ex) {
    }
  }

  /**
   * This returns a PSocket that connected to client.
   */
  public PTCPSocket accept() {
    boolean done = false;

    try {
      while (!done) { // (serverSocket_ != null) {

        if (PTCPServerSocket_Debug) {
          System.out.println(module_name_ + "Server is running");
        }

        Socket socket = server_socket_.accept();

        if (PTCPServerSocket_Debug) {
          System.out.println(module_name_ + "Just accept a socket");
        }

        String[] socketData = readSocketData(socket);
        String id = socketData[0];
        int type = Integer.parseInt(socketData[1]);
        long sentTime = Long.parseLong(socketData[2]);

        //System.out.println("Type is " + type);
        //System.out.println("Sent time is " + sentTime);

        PTCPSocketInfo pSockInfo = null;

        if (clients_.containsKey(id)) {
          if (PTCPServerSocket_Debug) {
            System.out.println(module_name_ + id + " is in the table");
          }

          pSockInfo = (PTCPSocketInfo) clients_.get(id);
        }
        else {
          //System.out.println(id + " is NOT in the table");
          pSockInfo = new PTCPSocketInfo(id);
          pSockInfo.setTxStartTime_(System.currentTimeMillis());
        }

        if (type == PTCPParameters.COMM_SOCKET) {
          String[] commSocketData = readCommSocketData(socket);
          int numStreams = Integer.parseInt(commSocketData[0]);
          long startRTT = Long.parseLong(commSocketData[1]);

          echoStartRTT(socket, startRTT);

          int[] result = readOptTCPWindowSize(socket);

          pSockInfo.setTcpWindowSize(result[0]);
          pSockInfo.setRtt(result[1]);
          if (PTCPServerSocket_Debug) {
            System.out.println(module_name_ + "startRTT is " + startRTT);
            System.out.println(module_name_ + "Optimum TCP Window Size " +
                               result[0]);
            System.out.println(module_name_ + "RTT is " + result[1]);

          }

          pSockInfo.setNumStreams(numStreams);
          pSockInfo.addCommSocket(socket);

          clients_.put(id, pSockInfo);

          if (PTCPServerSocket_Debug) {
            System.out.println(module_name_ + "pSockInfo NumStreams " +
                               pSockInfo.getNumStreams());
          }
        }
        else {
          if (PTCPServerSocket_Debug) {
            System.out.println(module_name_ + "pSockInfo NumStreams " +
                               pSockInfo.getNumStreams());
          }

          if (PTCPServerSocket_Debug) {
            System.out.println(module_name_ +
                               "New socket is registered to PSockInfo");
          }

          //socket.setReceiveBufferSize(625 * 1024); //pSockInfo.tcpWindowSize_);
          //socket.setSendBufferSize(625 * 1024); //pSockInfo.tcpWindowSize_);
          pSockInfo.addSocket(socket);

          if (PTCPServerSocket_Debug) {
            System.out.println(pSockInfo.isDone());
          }

          if (pSockInfo.isDone()) {
            //System.out.println("TCP Window Size " + pSockInfo.tcpWindowSize_);

            PTCPSocket pSocket = new PTCPSocket(pSockInfo.getNumStreams());
            pSocket.addSocket(pSockInfo.getSockets(), pSockInfo.getCommSocket());
            pSocket.setRTT(pSockInfo.getRtt());
            pSocket.setTxStartTime(pSockInfo.getTxStartTime());

            if (PTCPServerSocket_Debug) {
              System.out.println(module_name_ + "Returning a PSocket");
            }

            return pSocket;
          }

          clients_.put(id, pSockInfo);
        }

        if (PTCPServerSocket_Debug) {
          System.out.println(module_name_ + "End of if in Server accept()");
        }
      }
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }

    return null;
  }

  public String[] readCommSocketData(Socket socket) {
    String[] data = new String[2];

    try {
      DataInputStream dis = new DataInputStream(socket.getInputStream());

      int numStreams = dis.readInt();
      long startRTT = dis.readLong();
      data[0] = String.valueOf(numStreams);
      data[1] = String.valueOf(startRTT);
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }

    return data;
  }

  public int[] readOptTCPWindowSize(Socket socket) {
    int[] data = new int[] {
                 8192, 10};

    try {
      DataInputStream dis = new DataInputStream(socket.getInputStream());

      data[0] = dis.readInt();
      data[1] = dis.readInt();
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }

    return data;
  }

  public String[] readSocketData(Socket socket) {
    String[] data = new String[3];

    try {
      DataInputStream dis = new DataInputStream(socket.getInputStream());
      int idLength = dis.readInt();
      byte[] idB = new byte[idLength];

      dis.read(idB);

      String id = new String(idB);
      int type = dis.readInt();
      long sendTime = dis.readLong();

      data[0] = id;
      data[1] = String.valueOf(type);
      data[2] = String.valueOf(sendTime);
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }

    return data;
  }

  public void close() throws IOException {
    if (clients_ != null && clients_.size() > 0) {
      Enumeration keys = clients_.keys();
      while (keys.hasMoreElements()) {
        String key = (String) keys.nextElement();
        PTCPSocketInfo psockInfo = (PTCPSocketInfo) clients_.get(key);
        psockInfo.closeSockets();
        clients_.remove(key);

      }

    }
    server_socket_.close();
    clients_ = null;

  }

  /**
   * Send hand shake message back to client.
   */
  private void echoStartRTT(Socket socket, long sRTT) {
    byte[] header = null;
    OutputStream ostream = null;
    ByteArrayOutputStream thstream = new ByteArrayOutputStream(8);
    DataOutputStream headerStream = new DataOutputStream(thstream);

    try {
      headerStream.writeLong(sRTT);
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }

    header = thstream.toByteArray();

    if (header.length != 8) {
      System.out.println(module_name_ +
                         "Writing header length < reply header length");
    }

    try {
      ostream = socket.getOutputStream();
      ostream.write(header);
      ostream.flush();
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }
  }
}
